﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json.Linq;
using System.Collections;
using Newtonsoft.Json;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace AcfunUpload
{
    public static class Acfun
    {

        /*public static List<ACInfo> getAcList()
        {
            List<ACInfo> b = new List<ACInfo>();
            List<string> acList = new List<string>();
            Utils.console(4, "正在获取投稿信息，请稍等...");
            CookieContainer cc = DataSaving.acfunInfo.cc;
            string re = WebRequestHelper.http("http://www.acfun.cn/member/contributeList.aspx?pageSize=10&pageNo=1&channelId=0&contentId=",0,"",ref cc);
            JObject obj = JObject.Parse(re);
            if(!(bool)obj["success"])
            {
                Utils.console(4, "获取投稿失败");
                return null;
            }
            Utils.console(1, "帐号总投稿数："+obj["page"]["totalCount"]+"，正在获取被退稿的投稿...");
            JArray list = (JArray)obj["contents"];
            for (int i = 0; i < list.Count; i++)
            {
                
            }
        }
        public static List<VideoInfo> getVideoInfo(string ac)
        {
            CookieContainer cc = DataSaving.acfunInfo.cc;
            //http://www.acfun.cn/member/contributeEdit.aspx?contentId=3640125
            string re = WebRequestHelper.http("http://www.acfun.cn/member/contributeEdit.aspx?contentId="+ac, 0, "", ref cc);
            JObject obj = JObject.Parse(re);
            JArray list = (JArray)obj["videolist"];
            for (int i = 0; i < list.Count; i++)
            {

            }

        }*/

        /// <summary>
        /// 获取频道
        /// </summary>
        /// <returns></returns>
        public static Channel[] getChannels()
        {
            string re = WebRequestHelper.http(DataSaving.host + "/api/uploader/getchannels");
            JObject obj = JObject.Parse(re);
            if ((int)obj["error_code"] != 0)
            {
                return null;
            }
            JArray list = (JArray)obj["data"];
            ArrayList l = new ArrayList();
            for (int i = 0; i < list.Count; i++)
            {
                ArrayList temp = new ArrayList();
                JArray d = (JArray)obj["sub"];
                for (int c = 0; c < d.Count; c++)
                {
                    temp.Add(new SubChannel((string)d[c]["id"], (string)d[c]["name"]));
                }
                l.Add(new Channel((string)list[i]["id"], (string)list[i]["name"], (SubChannel[])temp.ToArray(typeof(SubChannel))));
            }
            return (Channel[])l.ToArray(typeof(Channel));
        }
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string getAccessToken()
        {
            string re = WebRequestHelper.http("http://www.acfun.cn/video/getYKToken.aspx?_=" + Utils.getTimestamp());
            JObject obj = JObject.Parse(re);
            if (!(bool)obj["success"])
            {
                return null;
            }
            return (string)obj["token"];
        }
        /// <summary>
        /// 获取Sign
        /// </summary>
        /// <param name="filesize">上传文件的大小，单位bety</param>
        /// <returns></returns>
        public static string getSign(string fileSize)
        {
            string re = WebRequestHelper.http("http://www.acfun.cn/video/getToken.aspx?fileSize=" + fileSize + "&time=" + +Utils.getTimestamp() + "&_=" + Utils.getTimestamp());
            JObject obj = JObject.Parse(re);
            if (!(bool)obj["success"])
            {
                return null;
            }
            return (string)obj["token"];
        }
        /// <summary>
        /// 获取上传服务器地址
        /// </summary>
        /// <param name="u">上传参数</param>
        /// <returns></returns>
        public static string getServerAddress(UploadInfo u)
        {
            string uploadServerHost = u.uploadServerHost;
            string uploadToken = u.uploadToken;
            string postData = "upload_token=" + uploadToken;
            string url = "http://" + uploadServerHost + "/api/get_server_address/";
            string re = WebRequestHelper.http(url, 1, postData);
            JObject obj = JObject.Parse(re);
            return (string)obj["server_address"];
        }
        /// <summary>
        /// 获取上传信息
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="fileSize">上传文件的大小，单位bety</param>
        /// <param name="u">ref</param>
        public static void getUploadInfo(ref UploadInfo u)
        {
            long timestamp = Utils.getTimestamp();
            string accessToken = u.accessToken;
            string fileName = u.fileName;
            string fileSize = u.fileSize;
            string sign = u.sign;
            string url = "https://aauth-vod.cn-beijing.aliyuncs.com/uploads/create.json?client_id=" + timestamp + "&access_token=" + accessToken + "&title=acfun_" + timestamp + "&tags=acfun&file_size=" + fileSize + "&file_name=" + fileName + "&isweb=1&target=cloud&sign=" + sign + "&_=" + timestamp;
            string re = WebRequestHelper.http(url);
            JObject obj = JObject.Parse(re);
            u.vid = (string)obj["video_id"];
            u.uploadServerHost = (string)obj["upload_server_uri"];
            u.uploadToken = (string)obj["upload_token"];
        }
        /// <summary>
        /// 创建上传文件在Youku Cloud
        /// </summary>
        /// <param name="u"></param>
        public static void commitVideo(UploadInfo u)
        {
            long timestamp = Utils.getTimestamp();
            string accessToken = u.accessToken;
            string clientId = u.clientId;
            string uploadToken = u.uploadToken;
            string uploadServerName = u.uploadServerName;
            string url = "https://aauth-vod.cn-beijing.aliyuncs.com/uploads/commit.json?access_token=" + accessToken + "&client_id=" + clientId + "&upload_token=" + uploadToken + "&upload_server_name=" + uploadServerName + "&_=" + timestamp;
            WebRequestHelper.http(url);
        }
        /// <summary>
        /// 提交vid到AcFun
        /// </summary>
        /// <param name="u"></param>
        /// <returns></returns>
        public static bool createVideo(ref UploadInfo u, AcfunInfo ac)
        {
            CookieContainer cc = ac.cc;
            string fileSize = u.fileSize;
            string vid = u.vid;
            string url = "http://www.acfun.cn/video/createVideo.aspx?type=youku&video_id=" + vid + "&filesize=" + fileSize;
            string re = WebRequestHelper.http(url, 0, "", ref cc);
            JObject obj = JObject.Parse(re);
            if ((bool)obj["success"])
            {
                u.sid = (string)obj["sid"];
                u.acVid = (string)obj["videoId"];
            }
            return (bool)obj["success"];

        }
        /// <summary>
        /// 提交视频信息
        /// </summary>
        /// <param name="title">标题</param>
        /// <param name="desc">简介</param>
        /// <param name="tags">tag</param>
        /// <param name="channelId">频道ID</param>
        /// <param name="titleImg">图片</param>
        /// <param name="allowAddTag">允许游客添加TAG</param>
        /// <param name="u"></param>
        /// <param name="ac"></param>
        /// <returns></returns>
        public static bool postVideoInfo(string title, string desc,int videoType, string[] tags, string channelId, string titleImg, bool allowAddTag, UploadInfo[] u, AcfunInfo ac)
        {
            string tag = "";
            string postData;
            CookieContainer cc = ac.cc;
            List<postAcInfo> info = new List<postAcInfo>();
            for (int i = 0; i < u.Length; i++)
            {
                info.Add(new postAcInfo(Convert.ToInt32(u[i].acVid), u[i].partName.Replace("{index}", (i+1) + ""), u[i].sid));
            }
            string jsonData = JsonConvert.SerializeObject(info);
            for (int i = 0; i < tags.Length; i++)
            {
                if (i == 0)
                {
                    tag += tags[i];
                }
                else
                {
                    tag += "," + tags[i];
                }
            }

            postData = "title=" + EncodingHelper.encodeutf8(title) +
                              "&description=" + EncodingHelper.encodeutf8(desc) +
                              "&tags=" + EncodingHelper.encodeutf8(tag) +
                              "&ctype="+videoType+
                              "&channelId=" + channelId +
                              "&titleImg=" + EncodingHelper.encodeutf8(titleImg) + "&bigCover=&videoInfo=" + EncodingHelper.encodeutf8(jsonData) +
                              "&allowAddTag=" + (allowAddTag ? 0 : 1);

            string url = "http://www.acfun.cn/member/contribute_video_save.aspx";
            string re = WebRequestHelper.http(url, 1, postData, ref cc);
            JObject obj = JObject.Parse(re);
            return (bool)obj["success"];
        }
        /// <summary>
        /// 获取上传图片token
        /// </summary>
        /// <returns></returns>
        public static string getUploadImgToken()
        {
            string url = "http://www.acfun.cn/appcms/api/qiniu/uptoken";
            string re = WebRequestHelper.http(url);
            JObject obj = JObject.Parse(re);
            return (string)obj["uptoken"];
        }
        /// <summary>
        /// 上传图片
        /// </summary>
        /// <param name="img">图像Image</param>
        /// <returns></returns>
        public static string uploadPic(Image img)
        {
            
            ImageFormat format = img.RawFormat;
            if(format != ImageFormat.Jpeg && format != ImageFormat.Png)
            {
                return null;
            }
            string ext = format == ImageFormat.Jpeg ? ".jpg" : "png";
            string token = getUploadImgToken();
            string re = WebRequestHelper.uploadPic(ImageToBytes(img), ext, token);
            JObject obj = JObject.Parse(re);
            string url = "http://imgs.aixifan.com/"+(string)obj["key"];

            return url;
        }
        /// <summary>
        /// Convert Image to Byte[]
        /// </summary>
        /// <param name="image"></param>
        /// <returns></returns>
        private static byte[] ImageToBytes(Image image)
        {
            ImageFormat format = image.RawFormat;
            using (MemoryStream ms = new MemoryStream())
            {
                if (format.Equals(ImageFormat.Jpeg))
                {
                    image.Save(ms, ImageFormat.Jpeg);
                }
                else if (format.Equals(ImageFormat.Png))
                {
                    image.Save(ms, ImageFormat.Png);
                }
                else if (format.Equals(ImageFormat.Bmp))
                {
                    image.Save(ms, ImageFormat.Bmp);
                }
                else if (format.Equals(ImageFormat.Gif))
                {
                    image.Save(ms, ImageFormat.Gif);
                }
                else if (format.Equals(ImageFormat.Icon))
                {
                    image.Save(ms, ImageFormat.Icon);
                }
                byte[] buffer = new byte[ms.Length];
                //Image.Save()会改变MemoryStream的Position，需要重新Seek到Begin
                ms.Seek(0, SeekOrigin.Begin);
                ms.Read(buffer, 0, buffer.Length);
                return buffer;
            }
        }
    }

}
